<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
        <!-- 用一个行列布局 -->
        <el-row type="flex" justify="space-between" align="middle" style="height: 40px">
          <el-col :span="20">
            <svg-icon icon-class="home" /><span>江苏传智播客教育科技股份有限公司</span>
          </el-col>
          <el-col :span="4">
            <el-row type="flex" justify="end">
              <!-- 两个内容 -->
              <el-col>负责人</el-col>
              <!-- 下拉菜单 element -->
              <el-col>
                <el-dropdown>
                  <span>
                    操作<i class="el-icon-arrow-down" />
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <!-- 添加一级部门为空 -->
                    <el-dropdown-item @click.native="doAdd('')">添加子部门</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <!-- 主体 -->
        <el-tree :data="list" default-expand-all>
          <template v-slot="scope">
            <el-row type="flex" justify="space-between" align="middle" style="height: 40px;width: 100%;">
              <el-col :span="20">
                <!-- <svg-icon icon-class="home" />{{scope.data.name}}<span></span> -->
                <i :class="scope.node.expandded ? 'icon-jianhaoshouqi' : 'icon-jiahao'" />
                <span> {{ scope.data.name }}</span>
              </el-col>
              <el-col :span="4">
                <el-row type="flex" justify="end">
                  <!-- 两个内容 -->
                  <el-col>{{ scope.data.manager }}</el-col>
                  <!-- 下拉菜单 element -->
                  <el-col>
                    <el-dropdown>
                      <span>
                        操作<i class="el-icon-arrow-down" />
                      </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native="doAdd(scope.data.id)">添加子部门
                        </el-dropdown-item>
                        <el-dropdown-item @click.native="doEdit(scope.data.id)">编辑子部门
                        </el-dropdown-item>
                        <el-dropdown-item @click.native="doDel(scope.data.id)">删除子部门
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-tree>
      </el-card>
    </div>
    <!-- 弹窗部分 -->
    <el-dialog v-if="showDialog" ref="DialogRef" :visible.sync="showDialog" :title="title" @close="doClose">
      <el-form v-if="showDialog" ref="formRef" label-width="120px" :model="form" :rules="formRules">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="form.code" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select v-model="form.manager" value>
            <el-option
              v-for="item in simpleEmployeelist"
              :key="item.id"
              :value="item.username"
              :label="item.username"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="form.introduce" />
        </el-form-item>
        <el-form-item>
          <el-button @click="doCancle">取消</el-button>
          <el-button type="primary" @click.native="doSubmit">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartments, getSimpleEmployee, doAddDepartment, getDelDepartment, getDepartmentById, editDepartment } from '@/api/departments'
import { arrayToTree } from '@/utils/ArrayToTree'
export default {
  data() {
    const validCode = (rule, value, callback) => {
      // console.log('传过来的数据',this.originList);
      let codeList = this.originList.map(item => item.code)
      // console.log('code...1111',codeList);
      if (this.title === '编辑部门') {
        // 先排除自己,把其他部门的名字放到codeList
        codeList = this.originList.filter(item => item.id !== this.pid).map(item => item.code)
      }
      if (codeList.includes(value)) {
        callback(new Error(value + '已被占用'))
      } else {
        callback()
      }
    }
    const validName = (rule, value, callback) => {
      // 此时相当于点击添加按钮,this.pid就是被点击按钮的id,要获取它的children的名zi
      let nameList = this.originList.filter(item => item.pid === this.pid).map(item => item.name)
      // 判断是否为编辑
      if (this.title === '编辑部门') {
        // 如果是编辑按钮,就要获取跟被点击按钮相同的pid,然后把他本身去掉
        const pid = this.originList.find(item => item.id === this.pid).pid
        nameList = this.originList.filter(item => item.pid === pid && item.id !== this.pid).map(item => item.name)
      }
      if (nameList.includes(value)) {
        callback(new Error(value + '已被占用'))
      } else {
        callback()
      }
    }
    return {
      // 依赖一份树形数据
      list: [],
      // 是否显示弹窗
      showDialog: false,
      // 被点击的部门id
      pid: '',
      // 弹窗dialog数据
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      // 表单校验规则
      formRules: {
        name: [
          { required: true, message: '部门名称为必填项', trigger: 'blur' },
          { min: 2, max: 50, message: '必填为1-50个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码为必填项', trigger: 'blur' },
          { min: 2, max: 50, message: '必填为1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人为必填项', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '部门介绍为必填项', trigger: 'blur' },
          { min: 2, max: 300, message: '必填为1-300个字符', trigger: 'blur' }
        ]
      },
      // 简单员工信息
      simpleEmployeelist: [],

      // 弹窗标题信息
      title: '新增部门',
      isEdit: false,
      originList: []// 校验数据
    }
  },
  created() {
    this.loadDepartments()
    this.loadSimpleEmployee()
  },
  methods: {
    // 加载部门数据
    async loadDepartments() {
      const { data: res } = await getDepartments()
      // 删除第一个数组中的元素
      res.data.depts.shift()
      this.originList = res.data.depts.filter(item => {
        return { id: item.id, name: item.name, pid: item.pid, code: item.code }
      })
      // console.log(res.data.depts);
      this.list = arrayToTree(res.data.depts, '')
      // 将平铺的数据变成树
      // console.log('数组变成树', this.list);
    },
    // 添加部门信息
    doAdd(id) {
      // console.log('id是',id);
      this.pid = id
      this.title = '新增部门'
      this.showDialog = true
      this.isEdit = false
    },
    // 编辑部门信息
    doEdit(id) {
      this.title = '编辑部门'
      this.pid = id
      this.showDialog = true
      this.isEdit = true
      // 加载通过id获取信息
      this.loadDepartmentById()
    },
    // 删除部门信息
    doDel(id) {
      this.$confirm('是否删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const { data: res } = await getDelDepartment(id)
        this.$message.success(res.message)
        // 刷新页面
        this.loadDepartments()
      }).catch(() => {
      })
    },
    // 加载员工数据
    async loadSimpleEmployee() {
      const { data: res } = await getSimpleEmployee()
      // console.log('简单员工信息',res.data);
      this.simpleEmployeelist = res.data
    },
    // 提交表单信息
    async doSubmit() {
      this.$refs.formRef.validate(async(valid) => {
        if (valid) {
          if (this.title === '编辑部门') {
            // 发送编辑请求
            const { data: res } = await editDepartment(this.form)
            // console.log('编辑部门', res)
            if (res.code === 10000) {
              this.$message.success(res.message)
              this.showDialog = false
              // 刷新页面
              this.loadDepartments()
            }
          } else {
            const obj = { ...this.form, pid: this.pid }
            console.log(obj)
            // 发送新增部门请求
            const { data: res } = await doAddDepartment(obj)
            // console.log(res)
            if (res.code === 10000) {
              this.$message.success(res.message)
              this.showDialog = false
              // 刷新页面
              this.loadDepartments()
            }
          }
        }
      })
    },
    // 通过id获取部门信息
    async loadDepartmentById() {
      const { data: res } = await getDepartmentById(this.pid)
      // console.log('通过id获取部门信息', res.data);
      this.form = res.data
    },
    // 点击取消,关闭弹窗
    doCancle() {
      this.showDialog = false
    },
    // 重置表单信息
    doClose() {
      this.form = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
      this.$refs.formRef.resetFields()
    }
  }
}
</script>
